
import java.sql.*;
import java.util.ResourceBundle;

/**
 * 实现事务:
 * connection.setAutoCommit(false);
 * connection.commit();
 * // 检查安全,按时回滚
 * connection.rollback();
 */
public class _01JDBC {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc1");

        String driver = resourceBundle.getString("driver");
        String url = resourceBundle.getString("url");
        String user = resourceBundle.getString("user");
        String password = resourceBundle.getString("password");


        try {
            // 注册驱动
            Class.forName(driver);
            // 获取连接

            connection = DriverManager.getConnection(url,user,password);
            // 将自动提交机制关闭.也就是开启事务
            connection.setAutoCommit(false);

            // 获取数据库操作对象
            String sql = "select ename as name ,sal as s from emp where ename like ? ";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,"K%");


            // 执行mysql语句.这里的executeQuery 就不要sql作为参数了
            resultSet = preparedStatement.executeQuery();
            int count  = 0;
            if(resultSet.next())
            {
                String name = resultSet.getString("name");
                int s = resultSet.getInt("s");
                System.out.println(name+ s);
                count++;
            }
            System.out.println(count);
            // 提交事物
            connection.commit();
        } catch (Exception e) {
            // 只要捕捉到了异常就先判断connection,保证数据的安全
            if(connection!=null){
                //
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {

            if(resultSet!=null){
                try {
                    connection.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }

            if (preparedStatement!=null){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
